﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wicresoft.SelfService.BL.Interface;
using NRemedy;
using NRemedy.Linq;
using Wicresoft.SelfService.DAO;

namespace Wicresoft.SelfService.BL
{
    public class KnowledgeService : IKnowledge,IDisposable
    {
        IUserSync _userInterface;

        public KnowledgeService(IUserSync UserInterface)
        {
            _userInterface = UserInterface;
        }

        public IEnumerable<HotTopRKM> GetTopViewRKMRecords(string User,string ARServer, string logInId, string logInPwd)
        {
            return GetRKMRecordsByKMAction("VIEWARTICLE", User, ARServer, logInId, logInPwd);
        }

        public IEnumerable<HotTopRKM> GetTopReferenceRKMRecords(string User,string ARServer, string logInId, string logInPwd)
        {
            return GetRKMRecordsByKMAction("USEARTICLE",User, ARServer, logInId, logInPwd);
        }

        private IEnumerable<HotTopRKM> GetRKMRecordsByKMAction(string KMAction, string User, string ARServer, string logInId, string logInPwd)
        {
            using (ARLoginContext context = new ARLoginContext(ARServer, logInId, logInPwd))
            {

                ARSet<RKMSessionRecording_KAM_Join> db = new ARSet<RKMSessionRecording_KAM_Join>(context, new ARServerDefaultFactory());
                var userinfo = _userInterface.getUserInfo(User);
                if (userinfo == null) throw new Exception("User not valid.");

                var q = from rkm in db
                        where (rkm.Company == userinfo.company || rkm.Company == "- Global -") && rkm.KMAction == KMAction
                        select rkm;

                List<RKMSessionRecording_KAM_Join> listRkm = q.ToList();
                List<HotTopRKM> return_value = new List<HotTopRKM>();
                foreach (var g in listRkm.GroupBy(r => r.sourceReqId))
                {
                    return_value.Add(new HotTopRKM
                    {
                        RKMId = g.Key,
                        ArticleTitle = g.First().ArticleTitle,
                        CreateTime = g.First().CreateDate,
                        Company = g.First().Company,
                        Times = g.Count(),
                        Version = g.First().ArticleVersion
                    });
                }

                return return_value.OrderByDescending(r=>r.Times);
            }
        }

        public void Dispose()
        {
            if (_userInterface != null && _userInterface is UserSync)
            {
                ((UserSync)_userInterface).Dispose();
            }
        }
    }
}
